package com.liu.project.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liu.project.aspect.RocmAspect;
import com.liu.project.aspect.WebLogAspect;
import com.liu.project.pojo.Certificate;
import com.liu.project.service.CertificateService;
import com.liu.project.utils.Message;
import com.liu.project.utils.UploadUtil;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import static com.liu.project.utils.UploadUtil.PATH;

/**
 * @program: project
 * @description: 证书展示控制
 * @author: 86187
 * @create: 2022-02-16 16:59
 **/

@Api(tags = "证书信息展示",description = "证书查询（分页）、展示、修改、增加")
@Controller
@RequestMapping("/api/certificate")
public class CertificateController {

    @Autowired
    CertificateService certificateService;

    @ApiOperation("添加证书(ADMIN权限)")
    @ApiResponses ({@ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "请求失败")})
    @PreAuthorize("hasAuthority('ADMIN')")
    @RocmAspect.OperLog//添加证书后重新调用聚类算法
    @PostMapping("/add")
    @ResponseBody
    public Message<Void> add(Certificate certificate) throws IOException {

        File file = new File(certificate.getImageUrl());
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));

        String saveUrl="/header/"+certificate.getName();
        String upload = UploadUtil.upload(multipartFile, saveUrl);
        certificate.setImageUrl(upload);
        if (certificateService.insertCertificate(certificate))
            return new Message<>(200,"请求成功");
        else return new Message<>(400,"请求失败");
    }


    @ApiOperation("修改证书信息(ADMIN权限)")
    @ApiResponses ({@ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "请求失败")})
    @PreAuthorize("hasAuthority('ADMIN')")
    @PostMapping("/update")
    @ResponseBody
    public Message<Void> update(Certificate certificate) throws IOException {

        Certificate certificateById = certificateService.findCertificateById(certificate.getCid());
            certificateById.setName(certificate.getName());
            certificateById.setMoney(certificate.getMoney());
            certificateById.setApplicationTime(certificate.getApplicationTime());
            certificateById.setContent(certificate.getContent());
            certificateById.setExamTime(certificate.getExamTime());
            certificateById.setWebsite(certificate.getWebsite());
            certificateById.setSubjectId(certificate.getSubjectId());

        File file = new File(certificate.getImageUrl());
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));

        String saveUrl="/header/"+certificate.getName();
        String upload = UploadUtil.upload(multipartFile, saveUrl);
        certificate.setImageUrl(upload);

        System.out.println(certificateById);
            if (certificateService.updateCertificate(certificateById))
            return new Message<>(200, "请求成功");
              else
               return new Message<>(400, "请求失败");
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @RocmAspect.OperLog//删除证书后重新调用聚类算法
    @ApiOperation("删除证书信息(ADMIN权限)")
    @ApiImplicitParam(name = "cid",value = "证书cid")
    @ApiResponses ({@ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "请求失败")})
    @GetMapping("/delete/{cid}")
    public Message<Void> delete(@PathVariable("cid") int cid){
        System.out.println(certificateService.deleteCertificate(cid));
        if (certificateService.deleteCertificate(cid))

            return new Message<>(200,"请求成功");
        else return new Message<>(400,"请求失败");

    }


    @WebLogAspect.OperLog
    @ApiOperation("点击获取一本证书信息")
   @ApiImplicitParam(name = "cid",value = "证书cid")
    @ApiResponse(code = 200,message = "请求成功",response = Message.class)
    @PostMapping("/findbyid/{cid}")
    @ResponseBody
    public Message<Certificate> findById(@PathVariable("cid") int cid){
        Certificate certificateById = certificateService.findCertificateById( cid);
          String realPath= PATH+certificateById.getImageUrl();
          certificateById.setImageUrl(realPath);
            return new Message<>(200,"请求成功",certificateById);
    }

    @ApiOperation("通过证书类型sid返回证书信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "sid",value = "证书类型sid"),
            @ApiImplicitParam(name = "pageNum",value = "第几页"),
            @ApiImplicitParam(name = "pageSize",value = "每页的数量")})
    @ApiResponse(code = 200,message = "请求成功",response = Message.class)
    @PostMapping("/findbysid/{sid}")
    @ResponseBody
    public Message<PageInfo<Certificate>> findBySid(@PathVariable("sid") int sid, int pageNum,int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Certificate> certificateBySid = certificateService.findCertificateBySid(sid);
        for (Certificate certificate : certificateBySid) {
            String realPath= PATH+certificate.getImageUrl();
            certificate.setImageUrl(realPath);
        }
        PageInfo<Certificate> certificatePageInfo = new PageInfo<>(certificateBySid);
        return new Message<>(200,"请求成功",certificatePageInfo);
    }

    @ApiOperation("模糊查询")
    @ApiImplicitParam(name = "key",value = "证书名称关键字")
    @ApiResponses (value = {@ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 404, message = "查无此证")})
    @PostMapping("/search/{name}")
    @ResponseBody
    public Message<List<Certificate>> findOne(@PathVariable("name") String name){
        List<Certificate> certificateByKey = certificateService.findCertificateByKey(name);
        for (Certificate certificate : certificateByKey) {
            String realPath= PATH+certificate.getImageUrl();
            certificate.setImageUrl(realPath);
        }
        if (certificateByKey==null){
            return new Message(404,"查无此证");
        }else
            return new Message<List<Certificate>>(200,"请求成功",certificateByKey);
    }

}
